package com.lagou.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

public class Configuration {
    private static DataSource dataSource;

    public static DataSource getDataSource(){
        return dataSource;
    }

    public static void setDataSource() throws PropertyVetoException {
        //获取节点内容
        ZkClient zkClient = new ZkClient("114.215.81.54:2181");
        Object DBInfo = zkClient.readData("/DBInfo");
        System.out.println(DBInfo);

        JSONObject jsonObject = JSON.parseObject(DBInfo.toString());
        //System.out.println(jsonObject.get("driver"));

        ComboPooledDataSource comboPooledDataSource =new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass((String)jsonObject.get("driver"));
        comboPooledDataSource.setJdbcUrl((String)jsonObject.get("url"));
        comboPooledDataSource.setUser((String)jsonObject.get("username"));
        comboPooledDataSource.setPassword((String)jsonObject.get("password"));

        dataSource =comboPooledDataSource;

        //注册节点内容监听
        zkClient.subscribeDataChanges("/DBInfo", new IZkDataListener() {
            public void handleDataChange(String path, Object data) throws Exception {
                System.out.println(path+"该节点内容被更新，更新后的内容"+data);
                //
                comboPooledDataSource.close();
                //重新设置数据库连接池
                setDataSource();
            }

            public void handleDataDeleted(String s) throws Exception {
                System.out.println(s+"该节点被删除");
            }
        });
    }
}
